import React, { PureComponent } from 'react';
import { connect } from "dva"
import { Input, Button, Menu, Icon, Tabs, Table, notification, Modal } from 'antd';
import ToolConfigModals from '../../components/toolConfigModals';
import Loading from "../../components/loading"
import { worker } from "../../utils/worker"
import "../../Common.less"
import "./index.less"
import moment from 'moment';
const { TabPane } = Tabs;
class Project extends PureComponent {
    constructor(props) {
        super(props)
        this.state = {
            count: 0,
            name: "",
            columns: [],
            treeData: [],
            allChecked: false,
            sortedInfo: null,
            st: null,
            qString: "",
            pagination: {
                pageSize: 5,
                pageNum: 1,
                isAsc: "desc",
                orderByColumn: "createTime"
            },
            sortlist: [{
                name: "项目名称",
                key: "name",
                isAsc: "desc",
                sort: "ascending"
            }, {
                name: "创建日期",
                key: "createTime",
                isAsc: "desc",
                sort: "ascending",

            }, {
                name: "更新日期",
                key: "updateTime",
                isAsc: "desc",
                sort: "ascending",

            }],

            loading: true,
            isloading: false,
            total: 0,
        }
        this.handleMenuClick = this.handleMenuClick.bind(this)
        this.tabChange = this.tabChange.bind(this)
        this.paginationChange = this.paginationChange.bind(this)
        this.addProject = this.addProject.bind(this)
        this.editProject = this.editProject.bind(this)
        this.queryprojects = this.queryprojects.bind(this)
        this.reset = this.reset.bind(this)
        this.openWorkSpace = this.openWorkSpace.bind(this)
        this.getData = this.getData.bind(this)
        this.collect = this.collect.bind(this)
        this.setVisible = this.setVisible.bind(this)
        this.lock = this.lock.bind(this)
        this.deleteProject = this.deleteProject.bind(this)
        this.modalConfirm = this.modalConfirm.bind(this)
        this.loopTreeNode = this.loopTreeNode.bind(this)
        this.goCusProps = this.goCusProps.bind(this)
        this.target=this.target.bind(this)
        this.refresh=this.refresh.bind(this)

    }
    loopTreeNode(data) {
        function loop(data) {
            if (data && data.length) {
                const len=data.length;
                for (let i = 0; i < len; i++) {
                    let item = data[i];
                    item.key = item.id + '';
                    item.title = item.name;
                    if (item.children && item.children.length) {
                        loop(item.children)
                    } else {
                        continue;
                    }
                }

            }
        }
        loop(data)
    }

    modalConfirm() {//
        if (this.state.modalContext && this.state.modalContext.context && this.state.modalContext.context.refresh) {
            this.state.modalContext.context.refresh()
        }
    }
    collect(e, item) {
        e.preventDefault()
        e.stopPropagation();

        this.props.updateProjectInfo({ id: item.id, collected: Number(!item.collected) + '' }, (res) => {
            notification.info({ message: !item.collected ? "已取消收藏!" : "收藏成功" })
            this.getData()
        }, (err) => {
            notification.info({ message: "接口异常!" })
        })
    }
    setVisible(e, item) {
        e.preventDefault()
        e.stopPropagation();

    }
    lock(e, item) {
        e.preventDefault()
        e.stopPropagation();
        this.props.updateProjectInfo({ id: item.id, locked: Number(!item.locked) + '' }, (res) => {
            notification.info({ message: !item.locked ? "已取消锁定!" : "锁定成功" })
            this.getData()
        }, (err) => {
            notification.info({ message: "接口异常!" })
        })
    }

    async componentDidMount() {
        if (!sessionStorage.getItem("isLogin")) {
            this.props.history.push("/login")
            return;
        }
        let tree = JSON.parse(JSON.stringify(await this.props.getStructureTree()))
        this.loopTreeNode(tree)
        if (tree) {
            this.props.setStructureTree(tree)
        }
        const columns = [
            {
                title: '项目名称',
                dataIndex: 'name',
                width: "250px",
                sortDirections: ['descend', 'ascend'],
                isAsc: "desc",
                ellipsis: true,
                sorter: true,
                render: (text, record) => {
                    return <span onClick={(e) => this.openWorkSpace(e, record)} className="title absMiddle"><label className="tmain">{text}</label><span className="iconBox absMiddle"><Icon className={record.collected == 0 ? 'active' : ''} onClick={e => this.collect(e, record)} type="star" theme={record.collected == 0 ? 'filled' : ''} /><Icon className={record.locked == 0 ? 'active' : ''} theme={record.locked == 0 ? 'filled' : ''} onClick={e => this.lock(e, record)} type="lock" /><Icon onClick={e => this.setVisible(e, record)} type="eye" /></span></span>
                }
            },
            {
                title: '设计阶段',
                dataIndex: 'designStageText',
                width: "90px",
                ellipsis: true,
            },
            {
                title: '设计标准',
                dataIndex: 'designStandardText',
                width: "90px",
                ellipsis: true,
            },
            {
                title: '年份',
                dataIndex: 'year',
                ellipsis: true,
                render: (text, record) => record.startYear + "~" + record.endYear
            },
            {
                title: '更新人',
                dataIndex: '更新人',
                width: "80px",
                ellipsis: true,
                render: (text, record) => "叶新隆"
            },
            {
                title: '创建时间',
                dataIndex: 'createTime',
                sortDirections: ['descend', 'ascend'],
                isAsc: "desc",
                sorter: true,
                ellipsis: true,
                render: text => moment(text).format("YYYY-MM-DD HH:mm:ss")
                // render: (text) => {
                //     return <span>{text ? new Date(text).toLocaleString(): text}</span>
                // }
            },
            {
                title: '更新时间',

                dataIndex: 'updateTime',
                sortDirections: ['descend', 'ascend'],
                isAsc: "desc",
                sorter: true,
                ellipsis: true,
                render: text => moment(text).format("YYYY-MM-DD HH:mm:ss")
                // render: (text) => {
                //     return <span>{text ? new Date(text).toLocaleString() : text}</span>
                // }
            },
            {
                title: '操作',
                key: 'action',
                width: "270px",
                render: (text, record) => <span className="operate absMiddle"><Button disabled={record.locked == 0} shape="round" icon="plus-square" onClick={(e) => this.openWorkSpace(e, record)}>打开</Button><Button disabled={record.locked == 0} shape="round" icon="edit" onClick={(e) => this.editProject(e, record)}>编辑</Button><Button disabled={record.locked == 0} shape="round" icon="delete" onClick={(e) => this.deleteProject(e, record)}>删除</Button></span>,
            },
        ];
        // <Button shape="round" icon="download">下载</Button>
        this.setState({
            columns
        })
        this.getData()
    }
    goCusProps(e) {
        e.preventDefault()
        const { history } = this.props;
        history.push('/cusProps')
    }
    addProject() {
        if (this.state.modalContext) {
            this.state.modalContext.updateModal({
                visible: true,
                title: "新建项目",
                event: { code: 'addProject' }
            });
        }
    }
    queryprojects(e) {
        e.preventDefault()
        this.getData()
    }
    async reset() {
        await this.setState({
            qString: ''
        })
        this.getData()
    }
    deleteProject(e, item) {
        e.preventDefault();
        let _this = this;
        Modal.confirm({
            title: "提示",
            content: "是否删除此项目?",
            cancelText: "取消",
            okText: "确定",
            onOk() {
                _this.props.deleteProject({ id: item.id }, res => {
                    _this.getData()
                }, err => {

                })
            },
            onCancel() {

            }
        })
    }
    editProject(e, item) {
        e.preventDefault()
        this.props.updateCurrentProject(item)
        if (this.state.modalContext) {
            this.state.modalContext.updateModal({
                visible: true,
                title: "编辑项目",
                event: { code: 'editProject' }
            });
        }
    }
    openWorkSpace(e, item) {
        e.preventDefault()
        this.setState({
            isloading: true
        })
        this.props.updateCurrentProject(item)
        this.props.history.push('/design')

    }
    handleMenuClick(e) {
        let { columns } = this.state;
        let item = this.state.sortlist[e.key]
        item.isAsc = item.isAsc == "asc" ? "desc" : "asc"
        item.sort = item.isAsc == 'asc' ? 'ascending' : 'descending'
        let item2 = columns.find(item => item.dataIndex == e.key)
        item2.isAsc = item.isAsc
        this.setState({
            columns: [...this.state.columns],
            sortlist: [...this.state.sortlist]
        })
    }
    async tabChange(e) {
        let { extra } = this.state;
        if (e == 1) {
            await this.setState({
                extra: {

                }
            })
            this.getData()
        } else if (e == 2) {
            await this.setState({
                extra: {
                    ...extra,
                    collected: '0',
                    locked: null
                }
            })
            this.getData()
        } else if (e == 3) {
            await this.setState({
                extra: {
                    ...extra,
                    locked: '0',
                    collected: null
                }
            })
            this.getData()
        }
    }
    getData() {
        let { dictlist } = this.props;
        let { extra,pagination,qString } = this.state
        this.setState({
            loading: true
        })
        if (this.props.getProjects) {

            this.props.getProjects({ ...pagination, name: qString, ...extra }, async (data) => {

                if (data && data.rows && data.rows.length) {
                    const len=data.rows.length
                    for (let i = 0; i < len; i++) {
                        let item = data.rows[i];
                        item.checked = false;
                        item.edit = false;
                        item.designStandardText = await worker.getDictName(dictlist, item.designStandard)
                        item.designStageText = await worker.getDictName(dictlist, item.designStage)
                    }
                }

                this.setState({
                    loading: false,
                    data: data ? data.rows : [],
                    total: data ? data.total : 0
                })
                if (this.props.onSuccess) {
                    this.props.onSuccess(data);
                }
            }, (error) => {

                if (this.props.onError) {
                    this.props.onError(error);
                }
                this.setState({
                    loading: false,
                    data: [],
                    total: 0
                })
            });
        }
    }
    async paginationChange(pagination2, filters, sorter, extra) {
        const {pagination}=this.state
        await this.setState({
            pagination: {
                orderByColumn:sorter.field||pagination.orderByColumn,
                pageNum: pagination2.current,
                pageSize:5,
                isAsc: sorter.order == "descend" ? "asc" : "desc"
            }
        })
        this.getData()
    }
    target(e, url) {
        e.preventDefault()
        this.props.history.push(url)
    }
    refresh(){
        this.getData()
    }
    render() {
        let { columns, data, pagination, total, sortlist, qString, loading, isloading } = this.state

        const content = sortlist.map((item, index) => {
            return (
                <Menu.Item key={index}>
                    {item.name}
                    <Icon type={"sort-" + item.sort} />
                </Menu.Item>
            )
        })
        const menu = (
            <Menu onClick={this.handleMenuClick}>
                {content}
            </Menu>
        );

        return (
            <div className="pcontent absMiddle">
                <div className="topNav absMiddle">
                    <div className="navLeft absMiddle">
                        <div className="logo"><Icon type="global" /></div>
                        <div className="title absMiddle">
                            <div className="absMiddle">智能桥梁设计</div>
                            <div className="absMiddle">Smart Bridge Design</div>
                        </div>
                    </div>
                    <div className="navMiddle absMiddle">
                        <div className="absMiddle">
                            <Icon type="solution" />
                            <div>个人空间</div>
                        </div>
                        <div onClick={e => {
                            let a=window.open("about:blank")
                            a.location=process.env.NODE_ENV=="production"?"/srd/libary":"/libary"
                        }} className="absMiddle">
                            <Icon type="code-sandbox" />
                            <div>构件资源库</div>
                            {/* <a href="/libary">构件资源库</a> */}
                        </div>
                        <div className="absMiddle">
                            <Icon type="history" />
                            <div>版本记录</div>
                        </div>
                        <div onClick={e => {
                            let a=window.open("about:blank")
                            a.location=process.env.NODE_ENV=="production"?"/srd/cusProps":"/cusProps"
                        }} className="absMiddle">
                            <Icon type="snippets" />
                            <div>自定义属性</div>
                            {/* <a href="/cusProps" target="_blank">总体信息</a> */}
                        </div>
                    </div>
                    <div className="navRight absMiddle">
                        <div className="portrait"><Icon type="user" /></div>
                        <div><Icon type="down" /></div>
                    </div>
                </div>
                <div className="main absMiddle">
                    <div className="tableMain absMiddle">
                        <div className="absMiddle tableSort">
                            
                            <Tabs defaultActiveKey="1" onChange={this.tabChange}>
                                <TabPane tab="全部" key="1">
                                </TabPane>
                                <TabPane tab="已收藏" key="2">
                                </TabPane>
                                <TabPane tab="已锁定" key="3">
                                </TabPane>
                            </Tabs>,
                            <div className="absMiddle sortMain">
                                <Input allowClear value={qString} onChange={e => {
                                    e.persist();
                                    this.setState({
                                        qString: e.target.value
                                    })
                                }} placeholder="项目名称"></Input>
                                <Button shape="round" style={{ marginLeft: '15px' }} onClick={e => this.queryprojects(e)} type="primary">查询</Button>
                                <Button shape="round" onClick={this.reset}>重置</Button>
                                {/* <Dropdown className="updateDate" overlay={menu}>
                                    <Button shape="round">
                                        排序 <Icon type="down" />
                                    </Button>
                                </Dropdown> */}
                                <Button shape="round" onClick={this.addProject} type="primary">添加</Button>
                            </div>
                        </div>
                        <div className="absMiddle tableBox2">
                            <Table  className="absMiddle" rowKey={record => record.id} onChange={this.paginationChange} pagination={{ 'current': pagination.pageNum, pageSize: pagination.pageSize, total }} loading={loading} columns={columns} dataSource={data} />
                        </div>
                    </div>
                </div>
                <ToolConfigModals
                    onLoaded={context => {
                        this.setState({ modalContext: context })
                    }}
                    parent={this}
                    refresh={this.refresh}
                    project={this.props.project ? this.props.project : {}}
                />
                <Loading visible={isloading}></Loading>
            </div>
        )
    }
}
export default connect(
    ({
        dict: { dictlist },
        project: { current },
    }) => ({
        dictlist,
        project: current
    })
    , dispatch => ({
        setStructureTree: (values) => dispatch({
            type: 'dict/setStructureTree',
            payload: values
        }),
        getStructureTree: (values) => dispatch({
            type: 'structure/getStructureTree',
            payload: values
        }),
        getProjects: (params, onSuccess, onError) => dispatch({
            type: 'project/getProjectsData',
            payload: {
                params,
                onSuccess,
                onError
            }
        }),
        deleteProject: (params, onSuccess, onError) => dispatch({
            type: 'project/deleteProject',
            payload: {
                params,
                onSuccess,
                onError
            }
        }),
        updateProjectInfo: (values, onSuccess, onError) => dispatch({
            type: 'project/updateProjectInfo',
            payload: {
                params: values,
                onSuccess,
                onError

            }
        }),
        updateCurrentProject: (project) => dispatch({
            type: 'project/updateCurrent',
            payload: project
        }),
       
    }))(Project);
